package com.kky.pp.adapter

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Vibrator
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.custom.base.base.SDEventManager
import com.custom.base.config.BaseConfig
import com.custom.base.type.AnimationActivityType
import com.custom.base.util.IntentUtil
import com.kky.pp.R
import com.kky.pp.bean.CardModelBean
import com.kky.pp.bean.TOListBean
import com.kky.pp.popup.TOListPopup
import com.kky.pp.dot.DotLogEventName
import com.kky.pp.dot.DotLogUtil
import com.kky.pp.activity.user.UserProfileInfoActivity
import com.kky.pp.activity.index.HomeCardPreloadHelper
import com.kky.pp.activity.index.IndexFragment
import com.kky.pp.callback.EventEnum
import com.kky.pp.callback.homeCardClickListener
import com.kky.pp.util.CollectionUtils
import com.kky.pp.util.DateUtils
import com.kky.pp.util.GlideUtil
import com.kky.pp.util.PermissionUtils
import com.kky.pp.util.TextUtil
import com.kky.pp.view.LinearLineIndicator
import com.kky.pp.view.TagCloudView
import com.kky.pp.view.cardstackview.CardStackLayoutManager
import com.youth.banner.Banner
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.util.BannerUtils
import io.rong.imkit.SpName
import io.rong.imkit.event.EnumEventTag
import io.rong.imkit.event.FirebaseEventTag
import io.rong.imkit.utils.FirebaseEventUtils
import kotlinx.coroutines.runBlocking
import java.util.Date

class CardStackAdapter(
    private var spots: List<CardModelBean> = emptyList(),
    private val indexfragment: IndexFragment,
    var mActivity: FragmentActivity,
    private var turnOns: Boolean,
    var turnOnsLimit: Int,
    private var newUserFlag: Boolean,
    private var continuousPassNumber: Int,
    var manager: CardStackLayoutManager,
) : RecyclerView.Adapter<CardStackAdapter.ViewHolder>() {
    private var upUserProfileListener: UpUserProfileListener? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return ViewHolder(inflater.inflate(R.layout.item_model_card, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.indexLocationContainer.visibility = View.GONE
        indexfragment.getUserActionViewId()?.isVisible = false
        if (!turnOns && position == turnOnsLimit) {
            BaseConfig.getInstance.setBoolean(SpName.userCard + position, false)
            holder.userContainer.visibility = View.GONE
            holder.indexTurnOnsContainer.visibility = View.VISIBLE
            holder.indexTurnOnsContainer.setOnClickListener {

            }
            holder.itemGoChooseTurnOns.setOnClickListener {
                TOListPopup.openDialog(mActivity).setOnClickSaveListener(object :
                    TOListPopup.OnClickSaveListener {
                    override fun clickSave(dataList: ArrayList<TOListBean>) {
                        SDEventManager.post(true, EnumEventTag.INDEX_LIKE_SWIPED.ordinal)
                    }

                })
            }
            holder.indexLocationContainer.visibility = View.GONE
        } else {
            if (continuousPassNumber == 5 && PermissionUtils.lacksPermission(
                    mActivity,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) && PermissionUtils.lacksPermission(
                    mActivity,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
            ) {
                continuousPassNumber = 0
                BaseConfig.getInstance.setBoolean(SpName.userCard + position, false)
                holder.userContainer.visibility = View.GONE
                holder.indexTurnOnsContainer.visibility = View.GONE
                holder.indexLocationContainer.visibility = View.VISIBLE
                holder.itemLocationTitleChild.visibility = View.VISIBLE
                holder.itemLocationLogo.visibility = View.VISIBLE
                indexfragment.getUserActionViewId()?.isVisible = false

                holder.indexLocationContainer.setOnClickListener {

                }
                holder.itemTurnOnLocation.setOnClickListener {
                    BaseConfig.getInstance.setBoolean(
                        SpName.todayFirstRequestLocation + DateUtils.getTime(
                            Date()
                        ), true
                    )
                    PermissionUtils.requestPermission(mActivity, {
                        SDEventManager.post(true, EnumEventTag.INDEX_LIKE_SWIPED.ordinal)
                        DotLogUtil.setEventName(DotLogEventName.LOCATION_PERMISSION_GRANTED)
                            .setRemark("402").commit(mActivity)
                    }, {
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", mActivity.packageName, null)
                        intent.data = uri
                        mActivity.startActivityForResult(intent, 10009)
                        DotLogUtil.setEventName(DotLogEventName.LOCATION_PERMISSION_GRANTED)
                            .setRemark("402").commit(mActivity)
                    },
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    )
                }
                DotLogUtil.setEventName(DotLogEventName.LOCATION_PERMISSION_GRANT_PAGE_WITH_APP_LAUNCH)
                    .commit(mActivity)
            } else {
                indexfragment.getUserActionViewId()?.isVisible = true
                HomeCardPreloadHelper.adapterPreloadLoad(mActivity, position, spots)
                runBlocking {
                    BaseConfig.getInstance.setBoolean(SpName.userCard + position, true)
                }
                holder.userContainer.visibility = View.VISIBLE
                holder.indexTurnOnsContainer.visibility = View.GONE

                val spot = spots[position]
                val drawable = ContextCompat.getDrawable(mActivity, R.mipmap.icon_index_member)
                holder.name.text =if (spot.userType==2) TextUtil().addIconsMember(mActivity,"${spot.nickName} · ${spot.age}",drawable)  else "${spot.nickName} · ${spot.age}"
                holder.online.visibility = if (spot.online == 1) View.VISIBLE else View.GONE
                holder.positioning.visibility = if (spot.nearby == 1) View.VISIBLE else View.GONE
                if (CollectionUtils.isNotEmpty(spot.images)) {
                    if (spot.images.size > 1) {
                        holder.userBanner.setUserInputEnabled(false)
                        val linearLineIndicator = LinearLineIndicator(mActivity)
                        linearLineIndicator.setIndicatorViewGravity(1)
                        holder.userBanner.indicator = linearLineIndicator
                        holder.userBanner.setIndicatorMargins(
                            IndicatorConfig.Margins(
                                0,
                                BannerUtils.dp2px(10f).toInt(),
                                0,
                                0
                            )
                        )
                    }
                    holder.userBanner.adapter =
                        PageLoaderAdapter(mActivity, spot.images, position = position)
                }
                val shake: Animation =
                    AnimationUtils.loadAnimation(mActivity, R.anim.shake) //加载动画资源文件
                holder.leftClick.homeCardClickListener(manager) {
                    holder.leftClick.isFocusableInTouchMode = true
                    if (it == EventEnum.CLICK) {
                        if (CollectionUtils.isNotEmpty(spot.images)) {
                            if (spot.images.size > 1) {
                                if (holder.userBanner.currentItem != 0) {
                                    holder.userBanner.currentItem =
                                        holder.userBanner.currentItem - 1
                                } else {
                                    val vibrator =
                                        mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                                    vibrator.vibrate(100)
                                    holder.itemView.startAnimation(shake)
                                }
                                FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Viewphotos.name)
                            } else {
                                val vibrator =
                                    mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                                vibrator.vibrate(100)
                                holder.itemView.startAnimation(shake)
                            }
                        } else {
                            val vibrator =
                                mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                            vibrator.vibrate(100)
                            holder.itemView.startAnimation(shake)
                        }
                    } else if (it == EventEnum.UP_SCROLL) {
                        upUserProfileListener?.upUserProfile(spot, holder.userBanner)
                    }
                }
                holder.rightClick.homeCardClickListener(manager) {
                    if (it == EventEnum.CLICK) {
                        if (CollectionUtils.isNotEmpty(spot.images)) {
                            if (spot.images.size > 1) {
                                if (holder.userBanner.currentItem != (spot.images.size - 1)) {
                                    holder.userBanner.currentItem =
                                        holder.userBanner.currentItem + 1
                                } else {
                                    holder.itemView.startAnimation(shake)
                                    val vibrator =
                                        mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                                    vibrator.vibrate(100)
                                }
                                FirebaseEventUtils.logEvent(FirebaseEventTag.Home_Viewphotos.name)
                            } else {
                                holder.itemView.startAnimation(shake)
                                val vibrator =
                                    mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                                vibrator.vibrate(100)
                            }
                        } else {
                            holder.itemView.startAnimation(shake)
                            val vibrator =
                                mActivity.getSystemService(AppCompatActivity.VIBRATOR_SERVICE) as Vibrator
                            vibrator.vibrate(100)
                        }
                    } else if (it == EventEnum.UP_SCROLL) {
                        upUserProfileListener?.upUserProfile(spot, holder.userBanner)
                    }
                }
                holder.bottomClick.setOnClickListener {
                    upUserProfileListener?.upUserProfile(spot, holder.userBanner)
                }
                if (spot.turnOnsListSize != null && spot.turnOnsListSize > 0) {
                    holder.txtTurnOnsSize.visibility = View.VISIBLE
                    holder.tagCloud.visibility = View.GONE
                    holder.txtTurnOnsSize.text =
                        "${spot.turnOnsListSize} ${mActivity.getString(R.string.turns_ons)}"
                    holder.txtTurnOnsSize.setOnClickListener {
                        val bundle = Bundle()
                        bundle.putString("userCode", spot.userCode)
                        bundle.putString("userCodeFriend", spot.friendUserCode)
                        bundle.putBoolean("turnOpen", true)
                        bundle.putBoolean("isIndex", true)
                        IntentUtil.startActivity(
                            UserProfileInfoActivity::class.java,
                            bundle,
                            animationStartType = AnimationActivityType.BOTTOM,
                            animationEndType = R.anim.anim_small_80
                        )
                    }
                } else {
                    holder.txtTurnOnsSize.visibility = View.GONE
                    holder.tagCloud.visibility = View.VISIBLE
                    val tags = arrayListOf<String>()
                    if (CollectionUtils.isNotEmpty(spot.interests)) {
                        repeat(spot.interests.size) {
                            tags.add(spot.interests[it].interest)
                        }
                    }
                    //tag最多显示3个
                    val newtags = arrayListOf<String>()
                    if (tags.size > 3) {
                        newtags.add(tags[0])
                        newtags.add(tags[1])
                        newtags.add(tags[2])
                    } else {
                        newtags.addAll(tags)
                    }
                    holder.tagCloud.setTags(newtags)
                }
            }
        }

        val preloadPosition = position + 2
        if (preloadPosition < spots.size) {
            val matchIndexBean = spots[preloadPosition]
            GlideUtil.preloadImage(mActivity, image = matchIndexBean.images[0].imageUrl)
        }
    }

    override fun getItemCount(): Int {
        return spots.size
    }

    fun setSpots(spots: List<CardModelBean>) {
        this.spots = spots
    }

    fun getSpots(): List<CardModelBean> {
        return spots
    }

    fun setTurnOns(turnOns: Boolean) {
        this.turnOns = turnOns
    }

    fun setNewUserFlag(newUserFlag: Boolean) {
        this.newUserFlag = newUserFlag
    }

    fun setContinuousPassNum(continuousPassNum: Int, topPosition: Int) {
        this.continuousPassNumber = continuousPassNum
        if (continuousPassNum == 5) {
            notifyItemChanged(topPosition)
        }
    }

    fun upUserProfileListener(upUserProfileListener: UpUserProfileListener) {
        this.upUserProfileListener = upUserProfileListener
    }


    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val name: TextView = view.findViewById(R.id.txtItemModelCardName)
        var online: TextView = view.findViewById(R.id.txtItemModelCardOnline)
        var positioning: TextView = view.findViewById(R.id.txtItemModelCardPositioning)
        var leftClick: View = view.findViewById(R.id.vItemModelCardOnlineLeftClick)
        var rightClick: View = view.findViewById(R.id.vItemModelCardOnlineRightClick)
        var bottomClick: View = view.findViewById(R.id.vItemModelCardOnlineBottomClick)
        var userBanner: Banner<*, *> = view.findViewById(R.id.bannerItemModelCard)
        var tagCloud: TagCloudView = view.findViewById(R.id.tagItemModelCard)
        var txtTurnOnsSize: TextView = view.findViewById(R.id.txtItemModelCardTurnOnsSize)
        var indexTurnOnsContainer: ConstraintLayout = view.findViewById(R.id.conItemModelCardTurnOnsContainer)
        var itemGoChooseTurnOns: TextView = view.findViewById(R.id.txtItemModelCardChooseTurnOns)
        var userContainer: FrameLayout = view.findViewById(R.id.frameItemModelCardUserContainer)
        var indexLocationContainer: ConstraintLayout = view.findViewById(R.id.conItemModelCardLocationContainer)
        var itemTurnOnLocation: TextView = view.findViewById(R.id.txtItemModelCardTurnOnLocation)
        var itemLocationTitleChild: TextView = view.findViewById(R.id.txtItemModelCardTurnOnLocationTitleChild)
        var itemLocationLogo: ImageView = view.findViewById(R.id.imgViewItemModelCardLocationLogo)
    }

    interface UpUserProfileListener {
        fun upUserProfile(spot: CardModelBean, banner: Banner<*, *>)
    }

}
